package com.tuanzi.loan.business.service.common.impl;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.DictionaryCode;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.collaborate.NewCollaborateChannelUser;
import com.tuanzi.loan.business.entity.common.CommProductChannel;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.repository.collaborate.CollaborateChannelUserRepository;
import com.tuanzi.loan.business.repository.common.CommProductChannelRepository;
import com.tuanzi.loan.business.repository.system.DictionaryRepository;
import com.tuanzi.loan.business.service.common.CommProductChannelService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.channel.ChannelSearchRequest;
import com.tuanzi.loan.vo.response.channel.ChannelSearchResponse;
import org.apache.commons.lang.StringUtils;
import org.primefaces.model.CheckboxTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Ray 2017/10/31
 */
@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class CommProductChannelServiceImpl implements CommProductChannelService {

	
	@Autowired
	private CommProductChannelRepository commProductChannelRepository;
	@Autowired
	private CollaborateChannelUserRepository collaborateChannelUserRepository;
	@Autowired
	private DictionaryRepository dictionaryRepository;
	
	public Integer checkRepeatChannelCode(CommProductChannel channel) {
		return commProductChannelRepository.checkRepeatChannelCode(channel);
	}

	@Override
	public List<CommProductChannel> findAll() {
		return commProductChannelRepository.findAll();
	}

	@Override
	public CommProductChannel findOne(Long id) {
		return commProductChannelRepository.findOne(id);
	}

	@Override
	public List<CommProductChannel> findAll(List<Long> ids) {
		return null;
	}

	@Override
	public CommProductChannel saveOrUpdate(CommProductChannel commProductChannel) {
		return commProductChannelRepository.save(commProductChannel);
	}

	@Override
	public Page<ChannelSearchResponse> list(PageSearcher<ChannelSearchRequest> pageSearcher) {
		return commProductChannelRepository.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
	}

	@Override
	public Integer checkDuplicatedChannelCode(Integer startChannelCode, Integer endChannelCode) {
		return commProductChannelRepository.checkDuplicatedChannelCode(startChannelCode, endChannelCode);
	}

	@Override
	public List<CommProductChannel> batchSave(List<CommProductChannel> commProductChannels) {
		return commProductChannelRepository.save(commProductChannels);
	}
	
	public int findChannelCount(CommProductChannel channel) {
		commProductChannelRepository.count();
		return 0;
	}

	@Override
	public List<CommProductChannel> findCurrentUserChannels() {

		String account = CurrentUser.get().getAccount();
		List<NewCollaborateChannelUser> channelUsers = collaborateChannelUserRepository.findByUserName(account);
		if(channelUsers == null || channelUsers.size() <=0){
			return Lists.newArrayList();
		}

		List<Integer> channelIdList = channelUsers.stream().map(NewCollaborateChannelUser::getChannelId).collect(Collectors.toList());

		return commProductChannelRepository.findAllByChannelCodeIn(channelIdList);
	}

	@Override
	public TreeNode createChannelGroupTreeNode(String selectedNodeStr) {
		List<CommProductChannel> all = this.findAll();

		//过滤没有分组的数据
		List<CommProductChannel> noNullList = all.stream().filter(commProductChannel -> commProductChannel.getChannelGroup() != null).collect(Collectors.toList());
		Map<Integer, List<CommProductChannel>> groupList = noNullList.stream().collect(Collectors.groupingBy(CommProductChannel::getChannelGroup));
		TreeNode root = new CheckboxTreeNode("Root", null);

		//获取字典
		List<Dictionary> channelCode = dictionaryRepository.findAllByCodes(Lists.newArrayList(DictionaryCode.CHANNEL_GROUP));

		//转换
		groupList.forEach((k,v) ->{
			Dictionary currentDic = channelCode.stream().filter(dictionary -> dictionary.getValue1().equals(k.toString())).findFirst().orElse(null);
			if(null != currentDic){
				//一级名称
				CommProductChannel tempCommChannel = new CommProductChannel();
				tempCommChannel.setChannelName(currentDic.getName());
				TreeNode secondNode = new CheckboxTreeNode(tempCommChannel, root);

				//为每个二级添加全部选项
				CommProductChannel allCommChannel = new CommProductChannel();
				allCommChannel.setChannelName("全部");
				allCommChannel.setChannelCode(-1000);
				allCommChannel.setChannelGroup(Integer.parseInt(currentDic.getValue1()));
				new CheckboxTreeNode(allCommChannel, secondNode);

				v.forEach(commProductChannel -> {
					CheckboxTreeNode thirdNode = new CheckboxTreeNode(commProductChannel, secondNode);
					if(StringUtils.isNotBlank(selectedNodeStr) && selectedNodeStr.contains(commProductChannel.getChannelCode().toString())){
						thirdNode.setSelected(true);
					}
				});
			}
		});

		return root;
	}
}
